package com.xiuyi.pixsynergybackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.xiuyi.pixsynergybackend.config.CosClientConfig;
import com.xiuyi.pixsynergybackend.controller.file.dto.UploadPictureResultDTO;
import com.xiuyi.pixsynergybackend.exception.BusinessException;
import com.xiuyi.pixsynergybackend.exception.ErrorCode;
import com.xiuyi.pixsynergybackend.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;


    /**
     * 上传图片
     *
     * @param multipartFile 文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPictureResultDTO uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);

        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFilename = String.format("%s_%s.%s", uuid, DateUtil.formatDate(new Date()), FileUtil.getSuffix(originalFilename));
        String uploadPath = String.format("%s/%s", uploadPathPrefix, uploadFilename);

        File file = null;
        try {
            // 创建临时文件（注意：createTempFile参数实际为前缀和后缀，此处路径处理可能不符合预期）
            // 生成的临时文件路径可能类似：/tmp/test/filename123456.tmp
            file = File.createTempFile(uploadPath, null);

            // 将上传文件内容转存到临时文件（可能抛出IO异常）
            multipartFile.transferTo(file);

            // 上传到COS对象存储（需确保cosManager已正确配置，且filepath符合存储路径规范）
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);

            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            // 计算宽高
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            // 封装返回结果
            UploadPictureResultDTO uploadPictureResultDTO = new UploadPictureResultDTO();
            uploadPictureResultDTO.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPictureResultDTO.setPicName(FileUtil.mainName(originalFilename));
            uploadPictureResultDTO.setPicSize(FileUtil.size(file));
            uploadPictureResultDTO.setPicWidth(picWidth);
            uploadPictureResultDTO.setPicHeight(picHeight);
            uploadPictureResultDTO.setPicScale(picScale);
            uploadPictureResultDTO.setPicFormat(imageInfo.getFormat());

            return uploadPictureResultDTO;
        } catch (Exception e) { // 捕获所有异常（建议细化异常类型）
            // 记录错误日志（包含原始文件路径信息）
            log.error("图片上传到对象存储失败", e);
            // 抛出自定义业务异常（注意：SYSTEM_ERROR可能不够具体）
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            deleteTempFile(file);
        }
    }

    /**
     * 校验文件
     *
     * @param multipartFile 文件
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空");
        // 1、校验文件大小
        long fileSize = multipartFile.getSize();
        final long ONE_MB = 1024 * 1024;
        ThrowUtils.throwIf(fileSize > 2 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
        // 2、校验文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件后缀
        final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误");
    }

    /**
     * 清理临时文件
     *
     * @param file 文件
     */
    private static void deleteTempFile(File file) {
        if (file == null) {
            return;
        }

        // 尝试删除临时文件（可能因权限等原因失败）
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            // 记录删除失败日志（建议使用warn级别）
            log.error("file delete error, filepath = " + file.getAbsolutePath());
        }
    }
}
